<script lang="ts" setup>
import { reactive, ref, onMounted } from "vue";
import { ElMessage, ElMessageBox } from "element-plus";
import CreateLabel from "./components/CreateLabeling.vue";
import CompleteHandle from "./components/CompleteHandle.vue";
import AddPlannedTime from "./components/AddPlannedTime.vue";
import { getDecalPage, changeStatus } from "/@/api/task";
import dayjs from "dayjs";
import { useRouter } from "vue-router";
import { exportExcel } from "/@/utils/index";
import { getUserList } from "/@/api/user";
import { getCargoList } from "/@/api/warehousing";
import { loadEnv } from "@build/index";
import timezone from "dayjs/plugin/timezone";
import utc from "dayjs/plugin/utc";
dayjs.extend(utc);
dayjs.extend(timezone);
const { VITE_PROXY_DOMAIN_REAL } = loadEnv();

defineOptions({
  name: "LabelTaskIndex"
});

const router = useRouter();
const tableData = ref([]);
const query = reactive({
  box_no: "",
  planning_time: "",
  status: null,
  currentPage: 1,
  pageSize: 15
});
const total = ref(0);
const createLabelingDia = ref(false);
const completeDia = ref(false);
const planDia = ref(false);
const planFormData = ref({
  id: "",
  planning_time: null
});
const completeFormData = ref({});
const whiteList = ["admin", "super", "warehouse"];
const role = JSON.parse(localStorage.getItem("authorized-token")).role; // 角色
const isAdmin = whiteList.includes(role);
// 选中的list
let checkList = ref([]);
const userList = ref([]);
const cargoList = ref([]);

const handleSelectionChange = val => {
  checkList.value = val;
};

// 导出excel
const exportTask = () => {
  const titleArr = [
    "箱麦",
    "数量",
    "贴标文件",
    "去向",
    "FBI ID",
    "Ref ID",
    "备注"
  ]; //表头中文名
  let data;
  if (!checkList.value.length) {
    if (!tableData.value.length) {
      ElMessage({
        type: "warning",
        message: "没有可导出数据请创建"
      });
    } else {
      data = tableData.value.map(item => {
        const { box_no, quantity, file, place_to_go, fba_id, ref_id, notes } =
          item;
        const obj = {
          box_no,
          quantity,
          file,
          place_to_go,
          fba_id,
          ref_id,
          notes
        };
        return obj;
      });
    }
  } else {
    data = checkList.value.map(item => {
      const { box_no, quantity, file, place_to_go, fba_id, ref_id, notes } =
        item;
      const obj = {
        box_no,
        quantity,
        file,
        place_to_go,
        fba_id,
        ref_id,
        notes
      };
      return obj;
    });
  }
  exportExcel(data, "贴标", titleArr, "sheetName");
};

onMounted(() => {
  getTableData();
});

const haveHandle = () => {
  if (!checkList.value.length) {
    return ElMessage({
      message: "请勾选任务",
      type: "warning"
    });
  } else {
    ElMessageBox.confirm("是否把状态置为进行中?", "提示", {
      confirmButtonText: "确定",
      cancelButtonText: "取消",
      type: "warning"
    })
      .then(() => {
        const multi_id = checkList.value.map(item => item.id);
        changeStatus({ multi_id }).then(() => {
          ElMessage({
            type: "success",
            message: "操作成功"
          });
          getTableData();
        });
      })
      .catch(() => {});
  }
};

const getTableData = () => {
  getDecalPage(query).then((res: any) => {
    if (Object.prototype.toString.call(res.data.data) === "[object Object]") {
      tableData.value = [];
    } else {
      // res.data.data.forEach(item => {
      //   if (item.planning_time)
      //     item.planning_time = new Date(item.planning_time).getTime() / 1000;
      //   if (item.completion_time)
      //     item.completion_time =
      //       new Date(item.completion_time).getTime() / 1000;
      // });
      tableData.value = res.data.data;
    }
    total.value = res.data.total;
  });
};

const getUserData = () => {
  if (isAdmin) {
    getUserList().then(({ data }) => {
      userList.value = data;
    });
  }
};

const getCargoData = () => {
  if (isAdmin) {
    getCargoList().then(({ data }) => {
      cargoList.value = data;
    });
  }
};

const handleSizeChange = val => {
  query.pageSize = val;
  getTableData();
};

const handleCurrentChange = val => {
  query.currentPage = val;
  getTableData();
};

const submitSuccess = () => {
  getTableData();
};

const filterStatus = val => {
  if (val === "1") {
    return "未完成";
  } else if (val === "2") {
    return "进行中";
  } else {
    return "已完成";
  }
};

const addPlanned = ({ id, planning_time }) => {
  planFormData.value = {
    id,
    planning_time: planning_time
      ? dayjs(planning_time * 1000)
          .tz("America/Los_Angeles")
          .format("YYYY-MM-DD")
      : ""
  };
  planDia.value = true;
};

const complete = row => {
  const obj = { ...row };
  obj.completion_time = obj.completion_time
    ? dayjs(obj.completion_time * 1000)
        .tz("America/Los_Angeles")
        .format("YYYY-MM-DD")
    : "";
  obj.bill_name = getBillName();
  obj.bill_description = "";
  obj.bill_rate = 0;
  completeFormData.value = obj;
  completeDia.value = true;
};

const getBillName = () => {
  const path = router.currentRoute.value.path;
  if (path === "/task/labeling") {
    return "贴标";
  } else if (path === "/task/transfer") {
    return "中转";
  } else if (path === "/task/liftingCabinet") {
    return "提柜";
  } else if (path === "/task/distribution") {
    return "一件代发";
  } else if (path === "/task/return") {
    return "退货";
  } else {
    return "";
  }
};

const downloadHandle = val => {
  let path = VITE_PROXY_DOMAIN_REAL + "/v1/download?path=" + encodeURI(val);
  window.location.href = path;
  // download({ path: encodeURI(val) }).then(res => {
  //   let fileName = "";
  //   let contentDisposition = res.headers["content-disposition"];
  //   if (contentDisposition) {
  //     fileName = window.decodeURI(
  //       res.headers["content-disposition"].split("=")[1]
  //     ); //取文件名
  //   }
  //   exportFile(res.data, fileName.slice(0, fileName.length - 1));
  // });
};

const createLabelEvent = () => {
  getUserData();
  getCargoData();
  createLabelingDia.value = true;
};
</script>

<template>
  <div class="labeling-task-warp">
    <el-card>
      <!-- search start -->
      <el-form :inline="true" :model="query" label-width="auto">
        <el-form-item label="箱麦:">
          <el-input v-model="query.box_no" />
        </el-form-item>
        <el-form-item label="规划时间:">
          <el-date-picker
            v-model="query.planning_time"
            type="date"
            format="YYYY/MM/DD"
            value-format="YYYY-MM-DD"
          />
        </el-form-item>
        <el-form-item label="状态:">
          <el-select v-model="query.status" clearable>
            <el-option label="未完成" :value="1" />
            <el-option label="进行中" :value="2" />
            <el-option label="已完成" :value="3" />
          </el-select>
        </el-form-item>
        <el-form-item label-width="0">
          <el-button type="primary" @click="getTableData">搜 索</el-button>
        </el-form-item>
      </el-form>
      <!-- search end -->

      <!-- btns start -->
      <div>
        <el-button type="primary" @click="createLabelEvent"
          >创建贴标任务</el-button
        >
        <el-button type="primary" @click="exportTask">导出任务</el-button>
        <el-button
          type="primary"
          @click="haveHandle"
          v-auth="['admin', 'super', 'warehouse']"
          >进行中按钮</el-button
        >
      </div>
      <!-- btns end -->

      <!-- tabel start -->
      <el-table
        ref="multipleTableRef"
        border
        :data="tableData"
        style="width: 100%; margin-top: 20px"
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55" />
        <el-table-column prop="identifier" label="编号" />
        <el-table-column prop="box_no" label="箱麦" />
        <el-table-column prop="quantity" label="数量" />
        <el-table-column label="贴标文件" width="120">
          <template #default="{ row }">
            <el-button
              type="success"
              size="small"
              plain
              @click="downloadHandle(row.file)"
              >下载贴标文件</el-button
            >
          </template>
        </el-table-column>
        <el-table-column prop="place_to_go" label="去向" />
        <el-table-column prop="type" label="类型">
          <template #default="{ row }">
            {{ row.type === 1 ? "按箱发货" : "按件发货" }}
          </template>
        </el-table-column>
        <el-table-column prop="fba_id" label="FBA ID" />
        <el-table-column prop="ref_id" label="Ref ID" />
        <el-table-column prop="notes" label="备注" />
        <el-table-column label="状态">
          <template #default="{ row }">
            {{ filterStatus(row.status) }}
          </template>
        </el-table-column>
        <el-table-column prop="planning_time" label="规划时间" width="120">
          <!-- <template #default="{ row }">
            {{
              row.planning_time
                ? dayjs(row.planning_time * 1000).format("YYYY-MM-DD HH:mm:ss")
                : ""
            }}
          </template> -->
        </el-table-column>
        <el-table-column prop="completion_time" label="完成时间" width="120">
          <!-- <template #default="{ row }">
            {{
              row.completion_time
                ? dayjs(row.completion_time * 1000).format(
                    "YYYY-MM-DD HH:mm:ss"
                  )
                : ""
            }}
          </template> -->
        </el-table-column>
        <el-table-column label="创建时间(加利福尼亚)" width="120">
          <template #default="{ row }">
            {{
              row.created_at
                ? dayjs(row.created_at * 1000)
                    .tz("America/Los_Angeles")
                    .format("YYYY-MM-DD HH:mm:ss")
                : ""
            }}
          </template>
        </el-table-column>
        <el-table-column label="更新时间(加利福尼亚)" width="120">
          <template #default="{ row }">
            {{
              row.updated_at
                ? dayjs(row.updated_at * 1000)
                    .tz("America/Los_Angeles")
                    .format("YYYY-MM-DD HH:mm:ss")
                : ""
            }}
          </template>
        </el-table-column>
        <el-table-column
          label="操作"
          width="210"
          fixed="right"
          v-auth="['admin', 'super', 'warehouse']"
        >
          <template #default="{ row }">
            <el-button type="primary" size="small" @click="complete(row)"
              >完成</el-button
            >
            <el-button type="primary" size="small" @click="addPlanned(row)"
              >添加规划时间</el-button
            >
          </template>
        </el-table-column>
      </el-table>
      <!-- tabel end -->

      <div style="display: flex; justify-content: flex-end; margin-top: 10px">
        <el-pagination
          v-model:currentPage="query.currentPage"
          v-model:page-size="query.pageSize"
          :page-sizes="[5, 10, 15, 20, 30]"
          background
          layout="total, sizes, prev, pager, next, jumper"
          :total="Number(total)"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 创建贴标任务dialog start -->
    <create-label
      v-model="createLabelingDia"
      :is-admin="isAdmin"
      :user-list="userList"
      :cargo-list="cargoList"
      @submit-success="submitSuccess"
    />
    <!-- 创建贴标任务dialog start -->

    <!-- 添加规划时间dialog start -->
    <add-planned-time
      v-model="planDia"
      :plan-form-data="planFormData"
      @submit-success="submitSuccess"
    />
    <!-- 添加规划时间dialog end -->

    <!-- 完成按钮dialog start -->
    <complete-handle
      v-model="completeDia"
      :complete-form-data="completeFormData"
      @submit-success="submitSuccess"
    />
    <!-- 完成按钮dialog end -->
  </div>
</template>

<style lang="scss" scoped>
::v-deep(.el-table) {
  .cell {
    text-overflow: unset !important;
  }
}
</style>
